package cn.jobstart.spider.spider;

import cn.jobstart.common.SkList;
import cn.jobstart.common.StringUtil;
import cn.jobstart.modelExt.SpiderMonitorExt;
import cn.jobstart.spider.downloader.SkDownloader;
import cn.jobstart.spider.listener.ISkSpiderListener;
import cn.jobstart.spider.pageProcessor.AbstractPageProcessor;
import com.itextpdf.tool.xml.pipeline.AbstractPipeline;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.SpiderListener;
import us.codecraft.webmagic.downloader.AbstractDownloader;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * @author sunke
 * @version 1.0
 * @Description
 * @date 2023-09-14 16:28
 */


public abstract class AbstractSpider extends Spider {


    private SpiderMonitorExt spiderMonitor;
    private AbstractPageProcessor pageProcessor;

    public AbstractSpider setDownloader(AbstractDownloader downloader) {
        this.downloader = downloader;
        return this;
    }

    private AbstractDownloader downloader=new SkDownloader();


    public AbstractSpider(PageProcessor pageProcessor, SpiderMonitorExt spiderMonitor) {
        super(pageProcessor);
        this.spiderMonitor = spiderMonitor;
    }

    public AbstractPageProcessor getPageProcessor() {
        return pageProcessor;
    }

    public AbstractSpider setPageProcessor(AbstractPageProcessor pageProcessor) {
        this.pageProcessor = pageProcessor;
        return this;
    }

    public String getId() {
        return spiderMonitor.getId();
    }

    @Override
    public String getUUID() {
        return getId();
    }

    public SpiderMonitorExt getSpiderMonitor() {
        return spiderMonitor;
    }

    public void setSpiderMonitor(SpiderMonitorExt spiderMonitor) {
        this.spiderMonitor = spiderMonitor;
    }


    public void addListener(SpiderListener listener) {


        List<SpiderListener> spiderListeners = getSpiderListeners();
        if (StringUtil.isNullOrEmpty(spiderListeners)) {
            spiderListeners = SkList.getInstance();
        }
        spiderListeners.add(listener);
        setSpiderListeners(spiderListeners);
    }


    @Override
    protected void initComponent() {
        super.initComponent();


    }

    @Override
    public void run() {

        List<SpiderListener> spiderListeners = getSpiderListeners();
        if (StringUtil.isNotObjEmpty(spiderListeners)) {
            for (SpiderListener listener : spiderListeners) {
                if (listener instanceof ISkSpiderListener) {
                    ((ISkSpiderListener) listener).onStart(this);
                }
            }
        }

        super.run();
        if (StringUtil.isNotObjEmpty(spiderListeners)) {
            for (SpiderListener listener : spiderListeners) {
                if (listener instanceof ISkSpiderListener) {
                    ((ISkSpiderListener) listener).onStop(this);
                }
            }
        }


    }


}
